package com.cmw.auntapp.ui;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.cmw.auntapp.R;
import com.cmw.auntapp.component.FileChoosePopWindow;
import com.cmw.auntapp.component.SelectSpinner;
import com.cmw.auntapp.constant.CommandType;
import com.cmw.auntapp.core.base.vo.DataResult;
import com.cmw.auntapp.core.util.BitmapUtil;
import com.cmw.auntapp.core.util.FormUtil;
import com.cmw.auntapp.core.util.SharedPreferencesUtil;
import com.cmw.auntapp.model.AttachmentModel;
import com.cmw.auntapp.model.AuntModel;
import com.cmw.auntapp.model.GvlistModel;
import com.cmw.auntapp.presenter.AuntPresenter;
import com.cmw.auntapp.presenter.LocationPresenter;
import com.cmw.auntapp.presenter.SysBasePresenter;
import com.cmw.auntapp.service.LocationService;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import io.reactivex.functions.Consumer;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static com.cmw.auntapp.constant.Constant.USER_MEMBERID_KEY;

/**
 *  @desc 个人资料编辑
 *  @auth Administrator
 *  @date 2021/4/11 21:10
 *  @contanct 13922111489/340360491@qq.com
 */
public class UserEditActivity extends BaseActivity {

    @BindView(R.id.rgp_sex)
    RadioGroup rgpSex;

    @BindView(R.id.sp_place)
    SelectSpinner spPlace;

    @BindView(R.id.sp_service_type)
    SelectSpinner spServiceType;

    @BindView(R.id.ib_id_card_front)
    ImageButton imgIdCardFront; //身份证正面

    @BindView(R.id.ib_id_card_back)
    ImageButton imgIdCardBack; //身份证反面

    @BindView(R.id.ib_upload_contract2)
    ImageView imgUploadContract2; //保险合同附件2

    @BindView(R.id.ib_del_contract2)
    ImageButton imgBtnDelContract2; //保险合同附件2删除按钮

    @BindView(R.id.ib_upload_contract3)
    ImageView imgUploadContract3; //保险合同附件3

    @BindView(R.id.ib_del_contract3)
    ImageButton imgBtnDelContract3; //保险合同附件3删除按钮

    @BindView(R.id.btn_save)
    Button btnSave;

    private FileChoosePopWindow pop;

    private ProgressDialog progressDialog; // 上传进度条

    AuntPresenter auntPresenter;

    private LocationPresenter locationPresenter;

    SysBasePresenter sysBasePresenter;

    private AuntModel auntInfoModel;

    private boolean isLoadData = true;

    private static final int[] VIEWIDS = {R.id.et_name, R.id.et_phone, R.id.rgp_sex, R.id.et_age, R.id.sp_place,
            R.id.sp_service_type, R.id.et_address, R.id.et_card_no, R.id.et_premium, R.id.et_end_date};
    private static final String[] FIELDNAMES = {"name", "phone", "sex", "age", "nativePlace",
            "serviceTypes", "address", "idcardNo", "premium", "endDate"};

    private LocationService.LocationBinder locationBinder;

    private boolean isConnectioned = false;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            locationBinder = (LocationService.LocationBinder)iBinder;
            locationBinder.updateLocation();
            isConnectioned = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            isConnectioned = false;
        }
    };

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_user_edit;
    }

    @Override
    void onInit(Bundle savedInstanceState) {
        setTitle(R.string.user_edit_title);
        auntPresenter = new AuntPresenter(this);
        locationPresenter = new LocationPresenter(this);
        sysBasePresenter = new SysBasePresenter(this);
        rgpSex.setOnCheckedChangeListener((group, checkedId) -> doInputChange());
        spPlace.setOnItemSelectedListener(pos -> doInputChange());
        spServiceType.setOnItemSelectedListener(pos -> doInputChange());
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume...");
        loadData();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onDestroy() {
        if (null != connection && isConnectioned) { // 解绑Service Connection
            unbindService(connection);
            connection = null;
        }
        super.onDestroy();
    }

    private void loadData() {
        if (!isLoadData) {
            return;
        }
        sysBasePresenter.getNativePlaceList();
        auntPresenter.get(); // 获取阿姨详细信息数据
        List<GvlistModel> serviceTypeDataList = sysBasePresenter.getServiceTypeList();
        spServiceType.setData(serviceTypeDataList);
    }

    //EidtText内容改变后的监听 value是控件ID，callback对应改变前，中，后的事件
    @OnTextChanged(value= {R.id.et_name, R.id.et_phone,R.id.et_age,
            R.id.et_address, R.id.et_card_no, R.id.et_premium,R.id.et_end_date}, callback=OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void doInputChange() {
        boolean isEmpty = FormUtil.isEmpty(this,VIEWIDS);
        int textColor = R.color.colorMoreGray;
        Drawable backgroundImg = ContextCompat.getDrawable(this, R.drawable.btn_big_nomal_cricle);
        if (!isEmpty) {
            textColor = R.color.color_333333;
            backgroundImg = ContextCompat.getDrawable(this, R.drawable.btn_big_active_cricle);
        }
        btnSave.setTextColor(ContextCompat.getColor(this, textColor));
        btnSave.setBackground(backgroundImg);
    }

    /**
     * 图片选择
     * 1.PictureSelector：
     *  https://gitee.com/mevermore/PictureSelector?_from=gitee_search#https://github.com/LuckSiege/PictureSelector/raw/master/app/demo/app_2020_11_22_2210_2.6.0.apk
     * 2.RxPermissions：
     *  https://blog.csdn.net/kingsley1212/article/details/95614714
     * @param view
     */
    @OnClick({R.id.ib_id_card_front, R.id.ib_id_card_back, R.id.fl_insure_contract})
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void doChooseImg(View view) {
        int viewId = view.getId();
        if (viewId == R.id.fl_insure_contract && checkUploadContractCount()) {
            return;
        }
        checkPermissionRequest();
        if (null == pop) pop = new FileChoosePopWindow(this);
        pop.setSourceViewId(view.getId());
        pop.showPopup();
    }

    public void checkPermissionRequest() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                Log.e(TAG, "相册权限申请："+(aBoolean ? "成功" : "失败"));
            }
        });
    }

    /**
     * 检查上传的合同数量
     * @return
     */
    private boolean checkUploadContractCount() {
        String uploadContract2Tag = (String)imgUploadContract2.getTag();
        String uploadContract3Tag = (String)imgUploadContract3.getTag();
        if (!TextUtils.isEmpty(uploadContract2Tag) && !TextUtils.isEmpty(uploadContract3Tag)) {
            Toast.makeText(this, "上传的意外保险合同照片数量不能超过两张", Toast.LENGTH_LONG).show();
            return true;
        }
        return false;
    }


    /**
     * 合同删除图标
     */
    @OnClick({R.id.ib_del_contract2, R.id.ib_del_contract3})
    public void delImage(View view) {
        int viewId = view.getId();
        ImageView imageContract = null;
        switch (viewId) {
            case R.id.ib_del_contract2: {
                imageContract = imgUploadContract2;
                break;
            }case R.id.ib_del_contract3: {
                imageContract = imgUploadContract3;
                break;
            }
        }
        imageContract.setTag(null);
        Drawable defaultImage = getResources().getDrawable(R.drawable.insure_example);
        imageContract.setImageDrawable(defaultImage);
        view.setVisibility(View.INVISIBLE);
    }

    /**
     * 保存数据
     *  姓名、手机号、性别、从事钟点工年龄、籍贯、服务类型、家庭住址、身份证号码、保险费、保险到期日
     *             et_name,et_phone,rgp_sex,et_age, sp_place, sp_service_type,et_address,et_card_no,et_premium,et_end_date
     *             //附件类：
     *             身份证正面,身份证反面,保险上传按钮,保险合同1,保险合同2
     *             ib_id_card_front,ib_id_card_back,fl_insure_contract,fm_upload_contract2/ib_upload_contract2,fm_upload_contract3/ib_upload_contract3
     */
    @OnClick(R.id.btn_save)
    public void doSave(View view){
        AuntModel auntModel = FormUtil.getValues(this,VIEWIDS, FIELDNAMES, AuntModel.class);
        Long memberId = SharedPreferencesUtil.getInstance(this).getLong(USER_MEMBERID_KEY);
        auntModel.setMemberId(memberId);
        setAttachmentIds(auntModel);
        Map<Integer,String> errInfo = auntPresenter.valid(auntModel);
        if (null != errInfo && !errInfo.isEmpty()) {
            FormUtil.displayErrs(this, errInfo);
            return;
        }
        if (auntInfoModel == null) {
            auntInfoModel = auntModel;
        } else {
            auntModel.setId(auntInfoModel.getId());
            auntInfoModel = auntModel;
        }
        auntPresenter.doSave(auntModel);
    }


    private void setAttachmentIds(AuntModel auntModel) {
        String idCardFrontAttId = (String)imgIdCardFront.getTag(); //将上传成功的附件ID存入TAG中
        String idCardBackAttId = (String)imgIdCardBack.getTag();
        String attachmentIds = null;
        if (TextUtils.isEmpty(idCardFrontAttId)) {
            idCardFrontAttId = "";
        }
        if (TextUtils.isEmpty(idCardBackAttId)) {
            idCardBackAttId = "";
        }
        String uploadContract2AttId = (String)imgUploadContract2.getTag(); //将上传成功的附件ID存入TAG中
        String uploadContract3AttId = (String)imgUploadContract3.getTag();
        String insureAttIds = null;
        if (TextUtils.isEmpty(uploadContract2AttId)) {
            uploadContract2AttId = "";
        }
        if (TextUtils.isEmpty(uploadContract3AttId)) {
            uploadContract3AttId = "";
        }
        attachmentIds = idCardFrontAttId + "," + idCardBackAttId;
        insureAttIds = uploadContract2AttId + "," + uploadContract3AttId;
        auntModel.setAttachmentIds(attachmentIds);
        auntModel.setInsureAttIds(insureAttIds);
    }


    @Override
    public boolean doSuccess(CommandType commandType, DataResult dataResult) {
        Object datas = dataResult.getDatas();
        switch (commandType) {
            case LIST:{ //省份数据
                Log.i(TAG, "省份数据.datas = "+datas.toString());
                fillNativeListData(dataResult);
                break;
            }case GET:{ // 阿姨详情数据
                if (null == datas) {
                    Log.e(TAG, "阿姨详情数据为空,可能是阿姨还未填写实名认证资料！");
                    return true;
                }
                Log.i(TAG, "阿姨详情数据.datas = "+datas.toString());
                fillFormData(dataResult);
                break;
            }case SAVE:{ // 阿姨数据保存
                Log.i(TAG, "阿姨数据保存.datas = "+datas.toString());
                JSONObject resultData =  (JSONObject)datas;
                Long auntId = resultData.getLong("id");
                if (null == auntInfoModel.getId()) {
                    auntInfoModel.setId(auntId);
                }
                updateAuntLocationByBindService();
                gotoBack();
                break;
            }case UPLOAD:{ // 文件上传
                Log.i(TAG, "附件数据.datas = "+datas.toString());
                JSONObject resultData =  (JSONObject)datas;
                setAttachmentIdToView(resultData);
                break;
            }
        }
        return true;
    }

    /**
     * 通过Bind Service 更新阿姨位置数据
     */
    private void updateAuntLocationByBindService() {
        Log.i(TAG, "通过Bind Service 更新阿姨位置数据...");
        Intent bindIntent = new Intent(this, LocationService.class);
        bindService(bindIntent, connection, BIND_AUTO_CREATE);
    }


    private void setAttachmentIdToView(JSONObject resultData) {
        View imageView = pop.getSelectView();
        if (imageView == null) {
            Toast.makeText(this, "找不到上传的图片对象，无法绑定附件ID", Toast.LENGTH_LONG).show();
            return;
        }
        Long attachmentId = resultData.getLong("attachmentId");
        int viewId = imageView.getId();
        switch (viewId) {
            case R.id.ib_id_card_front:
            case R.id.ib_id_card_back:{
                ImageButton imageButton = (ImageButton)imageView;
                imageButton.setTag(attachmentId.toString());
                break;
            }case R.id.ib_upload_contract2:
            case R.id.ib_upload_contract3:{
                ImageView imageContract = (ImageView)imageView;
                imageContract.setTag(attachmentId.toString());
                break;
            }
        }
    }



    /**
     * 为表单元素赋值
     * @param dataResult
     */
    private void fillFormData(DataResult dataResult) {
        JSONObject resultData =  (JSONObject)dataResult.getDatas();
        auntInfoModel = dataResult.getData(AuntModel.class);
        FormUtil.setValues(this, resultData, FIELDNAMES, VIEWIDS);
        List<AttachmentModel> idCardAttList = auntInfoModel.getIdcardAttList();
        List<AttachmentModel> insureAttList = auntInfoModel.getInsureAttList();
        BitmapUtil bitmapUtil = BitmapUtil.getBtimapUtil(this);
        if (null != idCardAttList && !idCardAttList.isEmpty()) {
            AttachmentModel idCardFront = idCardAttList.get(0);
            imgIdCardFront.setTag(idCardFront.getId().toString());
            bitmapUtil.setDrawableByNetWork(imgIdCardFront, idCardFront.getFilePath());
            if (idCardAttList.size() == 2) {
                AttachmentModel idCardBack = idCardAttList.get(1);
                imgIdCardBack.setTag(idCardBack.getId().toString());
                bitmapUtil.setDrawableByNetWork(imgIdCardBack, idCardBack.getFilePath());
            }
        }
        if (null != insureAttList && !insureAttList.isEmpty()) {
            AttachmentModel insureContract1 = insureAttList.get(0);
            imgUploadContract2.setTag(insureContract1.getId().toString());
            bitmapUtil.setDrawableByNetWork(imgUploadContract2, insureContract1.getFilePath());

            if (insureAttList.size() == 2) {
                AttachmentModel insureContract2 = insureAttList.get(1);
                imgUploadContract3.setTag(insureContract2.getId().toString());
                bitmapUtil.setDrawableByNetWork(imgUploadContract3, insureContract2.getFilePath());
            }
        }
        doInputChange(); // 用来显示是否激活保存按钮
    }

    private void fillNativeListData(DataResult dataResult) {
        List<GvlistModel> placeDataList = dataResult.getDataList(GvlistModel.class);
        spPlace.setData(placeDataList);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        isLoadData = false;
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调

                    images = PictureSelector.obtainMultipleResult(data);
                    doUpload(images);

//                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    break;
            }
        }
    }

    public void doUpload(List<LocalMedia> images) {
        if (null == images || images.isEmpty()) {
            Toast.makeText(this, "请选择要上传的图片", Toast.LENGTH_LONG).show();
            return;
        }
        String imagePath = images.get(0).getPath();
        File file = new File(imagePath);
        Bitmap imgae = BitmapUtil.getBtimapUtil(this).fileToBitmap(imagePath);
        int viewId = pop.getSourceViewId();
        String formType = "-1";
        switch (viewId) {
            case R.id.ib_id_card_front:
            case R.id.ib_id_card_back:{
                ImageButton imgIdCard = null;
                if (viewId == R.id.ib_id_card_back) {
                    formType = "2";
                    imgIdCard = imgIdCardBack;
                } else {
                    formType = "1";
                    imgIdCard = imgIdCardFront;
                }
                imgIdCard.setImageBitmap(imgae);
                imgIdCard.setTag("0"); //代表已经选择了图片
                pop.setSelectView(imgIdCard);
                break;
            } case R.id.fl_insure_contract:{
                formType = "3";
                Object imgContract2Tag = imgUploadContract2.getTag();
                Object imgContract3Tag = imgUploadContract3.getTag();
                ImageView imgContract = null;
                ImageButton imgBtnDelContract = null;
                if (imgContract3Tag == null) { //未上传保险照片
                    imgContract = imgUploadContract3;
                    imgBtnDelContract = imgBtnDelContract3;
                }else if (imgContract2Tag == null) { //未上传保险照片
                    imgContract = imgUploadContract2;
                    imgBtnDelContract = imgBtnDelContract2;
                }
                if (null == imgContract) {
                    Toast.makeText(this, "上传的意外保险合同照片数量不能超过两张", Toast.LENGTH_LONG).show();
                    return;
                }
                imgContract.setImageBitmap(imgae);
                imgContract.setTag("0"); //代表已经选择了图片
                imgBtnDelContract.setVisibility(View.VISIBLE);
                pop.setSelectView(imgContract);
                break;
            }
        }

        Map<String,String> params = new HashMap<>();
        params.put("formType", formType);
        if (auntInfoModel != null) {
            Long formId = auntInfoModel.getId();
            if (formId == null) {
                formId = -1L;
            }
            params.put("formId", formId.toString());
        }
        ProgressDialog progress = getProgress();
        progress.show();
        sysBasePresenter.uploadFile(params, file, (long cur, long total) -> {
            progress.setMax((int)total);
            progress.setProgress((int)cur);
            Log.i(TAG, String.format("上传进度：{current: %d KB, total: %d KB}", cur, total));
            if (cur >= total) {
                progress.dismiss();
                runOnUiThread(() -> Toast.makeText(UserEditActivity.this, "上传成功", Toast.LENGTH_LONG).show());
            }
        });
    }

    private ProgressDialog getProgress() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 水平进度条
        }
        return progressDialog;
    }

}